package cn.gok.gokhappymall.controller;

import cn.gok.gokhappymall.common.ServerResponse;
import cn.gok.gokhappymall.service.OrderService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author: chenfan
 * @Description:
 */

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    OrderService orderService;



    @GetMapping ("/create.do")
    public ServerResponse createOrder(Integer shippingId) throws IOException {
        Integer userId = 1;
        return orderService.createOrder(shippingId, userId);
    }


    /**
       当支付宝完成操作后，主动的调用此请求，回显支付结果
     */
    @RequestMapping("/alipay_callback.do")
    public String alipayCallback(HttpServletRequest request)  {


        Map<String ,String> map = new HashMap<>();

        //遍历支付宝返回的结果，{ "姓名"：["zhangsan"],      "兴趣"：["唱歌"，"跳舞"，"看电影"]}
        //                 --------->{ "姓名"："zhangsan", "兴趣"："唱歌，跳舞，看电影"}
        Map<String, String[]> parameterMap = request.getParameterMap();

        System.out.println(Arrays.toString(parameterMap.get("fund_bill_list")));

        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            String key = entry.getKey();
            String[] values = entry.getValue();

            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length -1)?valueStr + values[i]: valueStr+values[i] +",";
            }
            map.put(key,valueStr);
        }

//        map.remove("sign");
        map.remove("sign_type ");

        System.out.println(map);
        try {
            boolean isRsaCheckV2 = AlipaySignature.rsaCheckV1(map, Configs.getAlipayPublicKey(), "utf-8", "RSA2");
            System.out.println("isRsaCheckV2: " + isRsaCheckV2);
            if (!isRsaCheckV2){
                log.info("支付宝支付信息验证失败");
                return "fail";
            }
        } catch (AlipayApiException e) {
            log.error("支付宝回调验证失败，出现异常", e);
        }


        ServerResponse serverResponse = orderService.alipayCallback(map);
        if (serverResponse.isSuccess()){
            System.out.println("支付成功。。。。");
            return "success";
        }
        return "fail";
    }


    @GetMapping ("/pay.do")
    public ServerResponse pay(Long orderNo, HttpSession session) throws IOException {

        //此时获取路径的目的在于存放二维码图片
        String path = ResourceUtils.getURL("classpath:").getPath();
        //在类路径下创建 static/upload路径
        File upload = new File(path,"static/erweima");

        if (!upload.exists()){
            upload.mkdirs();
        }

        ServerResponse serverResponse = orderService.pay(orderNo, 1, upload.getAbsolutePath());
        return serverResponse;
    }
}
